package com.yunzai.file.service.impl;

import com.yunzai.file.config.FileUploadConfig;
import com.yunzai.file.service.IFileDownloadService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileDownloadServiceImpl implements IFileDownloadService {

    private static final Log log = LogFactory.getLog(FileDownloadServiceImpl.class);

    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Override
    public Resource downloadFile(String filename) {
        Path ROOT_PATH = Paths.get(fileUploadConfig.getStorage().getPath());
        return getFile(ROOT_PATH, filename);
    }

    @Override
    public Resource avatar(String filename) {
        Path ROOT_PATH = Paths.get(fileUploadConfig.getStorage().getAvatarPath());
        return getFile(ROOT_PATH, filename);
    }

    private Resource getFile(Path ROOT_PATH, String filename) {
        // 1. 路径安全校验（防止路径遍历攻击）
        Path filePath = ROOT_PATH.resolve(filename).normalize();
        if (!filePath.startsWith(ROOT_PATH)) {
            throw new IllegalArgumentException("路径不存在！");
        }

        // 2. 创建资源对象
        Resource resource = null;
        try {
            resource = new UrlResource(filePath.toUri());
        } catch (MalformedURLException e) {
//            log.error("文件不存在！",e);
            throw new RuntimeException("文件不存在！");
        }

        // 3. 检查文件是否存在
        if (!resource.exists() || !resource.isReadable()) {
            throw new RuntimeException("文件不存在！");
        }
        return resource;
    }
}
